package com.core.shared.encrypt;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/7/20
 * Time: 9:37
 * To change this template use File | Settings | File Templates.
 */
public class MD5Handle {

    private static final String input_charset = "utf-8";
    private static final String key = "";
    private static MessageDigest md5 = null;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException("MD5 实例化失败!");
        }
    }

    /**
     * md5签名
     * 对应md5.js
     *
     * @param text
     * @return
     */
    public static String sign(String text) {
        return DigestUtils.md5Hex(getContentBytes(text + key, input_charset));
    }

    /**
     * 验证md5签名串
     *
     * @param sign
     * @param text
     * @return
     */
    public static boolean verify(String sign, String text) {
        String mysign = DigestUtils.md5Hex(getContentBytes(text + key, input_charset));
        if (mysign.equals(sign)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 第二种md5加密
     *
     * @param inStr
     * @return
     */
    public static String md5Encode(String inStr) {
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("指定的编码集不对,目前指定的编码集:" + charset);
        }
    }


}
